import base64
import calendar
import datetime
import hashlib
import hmac
import random
import string
import time
import requests
from datetime import datetime

from httprunner import __version__


def get_httprunner_version():
    return __version__


def sum_two(m, n):
    return m + n


def get_last_today():
    # 获取当前时间
    now = datetime.datetime.now()
    # 获取今天零点
    zeroToday = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,
                                         microseconds=now.microsecond)
    # 获取23:59:59
    lastToday = zeroToday + datetime.timedelta(hours=23, minutes=59, seconds=59)
    last_today = lastToday.strftime("%Y-%m-%d %H:%M:%S")
    return last_today


def get_zero_today():
    now = datetime.datetime.now()
    # 获取今天零点
    zeroToday = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,
                                         microseconds=now.microsecond)
    zero_today = zeroToday.strftime("%Y-%m-%d %H:%M:%S")
    return zero_today


def random_str():
    # 从A-Z0-9生成指定数量的随机字符：
    ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 9)).upper()
    uuid = "355" + ran_str
    print(uuid)


# 设置用例等待时间
def sleep(response, n_secs):
    if response.status_code == 200:  # 接口请求code等于200 则等待n_secs 秒
        time.sleep(n_secs)
    else:  # 接口请求code不等于200 则等待0.5 秒
        time.sleep(0.5)


def get_calender():
    timestamp = calendar.timegm(time.gmtime())
    print(timestamp)
    return timestamp


def get_calender_tz(tz_offset_hours=0):
    now_in_utc = int(time.time())
    timestamp = now_in_utc - tz_offset_hours * 3600
    print(timestamp)
    return timestamp


def get_calender_time():
    timestamp = get_calender() + 300
    print(timestamp)
    return timestamp


def get_gps_time(second):
    timestamp = get_calender() - second
    # print(timestamp)
    return timestamp


def image_path():
    img_path = time.strftime("%Y/%m/%d/%H/%M-%S", time.localtime()) + ".jpg"
    print(img_path)
    return img_path


def start_timestamp(tz_offset_hours=0):
    now_in_utc = int(time.time())
    start_ts_in_utc = now_in_utc - now_in_utc % 86400
    start_ts_by_offset = start_ts_in_utc - tz_offset_hours * 3600
    print(start_ts_by_offset)
    return start_ts_by_offset


def get_secret_key(appid):
    secret_key = {
        "1025545": "d39c77c02tt2d0238318d18dba649555",
        "1168730": "d39c77c02tt2d0238318d18dba649666",
        "1168731": "d39c77c02tt2d0238318d18dba649777",
        "1168732": "d39c77c02tt2d0238318d18dba649888",
        "1168733": "d39c77c02tt2d0238318d18dba649999",
        "1168734": "d39c77c02tt2d0238318d18dba659999",
        "393": "d39c77c02tt2d0238318d18dba649555"
    }
    for key, value in secret_key.items():
        print(key)
        if key == appid:
            ak = value
            break
    print(ak)
    return ak


def sign_body(body):
    data_new = ""
    for key, value in sorted(body.items()):
        if key != "access_key" and key != "sign" and key != "userid":
            data_new += key + "=" + str(value) + "&"
    sk = get_secret_key(body["appid"])
    sign_data = (hmac.new(bytes(sk, encoding="utf-8"), base64.b64encode(data_new.strip("&").encode("utf-8")),
                          hashlib.sha1).hexdigest()).upper()
    print(data_new.strip("&"))
    return sign_data


def setup_post_request(request):
    print(request)
    body = request.get("data")
    sign = sign_body(body)
    request["data"]["sign"] = sign


def request_post():
    url = "http://device-test.tange365.com/record/report"
    data = {
        "uuid": "3A3MQKZAKGCY",
        "ossid": "5",
        "tag": "body",
        "is_pay": 0,
        "start_time": get_calender(),
        "end_time": get_calender(),
        "image_path": image_path(),
        "user_id": "393",
        "mac": "112233445566",
        "sdkver": 89
    }
    print(data)
    res = requests.post(url=url, data=data)
    print (res.json())


def requests_post():
    url = "http://api-test.tange365.com/app/device/report_gps"
    data = {
        "uuid": "3A3LST6SNYYL",
        "position": [
            {
                "time": get_gps_time(12),
                "latitude": 22.658997,
                "longitude": 114.069038,
                "speed": 5,
                "brg": 300
            },
            {
                "time": get_gps_time(8),
                "latitude": 22.650457,
                "longitude": 114.060585,
                "speed": 6,
                "brg": 200
            },
            {
                "time": get_gps_time(6),
                "latitude": 22.63464,
                "longitude": 114.06469,
                "speed": 8,
                "brg": 156
            },
            {
                "time": get_gps_time(3),
                "latitude": 22.62579,
                "longitude": 114.061241,
                "speed": 18,
                "brg": 120
            }
        ]
    }
    print(data)
    res = requests.post(url=url, data=data)
    print(res.json())



if __name__ == "__main__":
    requests_post()
